package com.tanhua.sso.service;

/**
 * Created by 景银泰
 * date 2020-11-09 16:31
 * Description :
 * Version :
 */

import com.tanhua.sso.tools.ValidateCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class SmsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsService.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public static final String REDIS_KEY_PREFIX = "CHECK_CODE_";
    /**
     * 发送验证码短信
     *
     * @param mobile
     */
    public String sendSms(String mobile) {

        String validateCode = ValidateCodeUtils.generateValidateCode4String(6);
        System.out.println("**********************************");
        System.out.println("发送验证码短信");
        System.out.println(mobile + "验证码为：" + validateCode);

      /*  redisTemplate.expire(mobile,4, TimeUnit.MINUTES);
        redisTemplate.boundValueOps(mobile).set(validateCode);*/

        return validateCode;
    }


    /**
     * 发送验证码
     *
     * @param mobile
     * @return
     */
    public Map<String, Object> sendCheckCode(String mobile) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            String redisKey = "CHECK_CODE_" + mobile;
            String value = this.redisTemplate.opsForValue().get(redisKey);
            if (StringUtils.isNotEmpty(value)) {
                result.put("code", 1);
                result.put("msg", "上一次发送的验证码还未失效");
                return result;
            }
//            String code = this.sendSms(mobile);
            String code = "123456";
            if (null == code) {
                result.put("code", 2);
                result.put("msg", "发送短信验证码失败");
                return result;
            }

            //发送验证码成功
            result.put("code", 3);
            result.put("msg", "ok");

            //将验证码存储到Redis,2分钟后失效
            this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(2));

            return result;
        } catch (Exception e) {

            LOGGER.error("发送验证码出错！" + mobile, e);

            result.put("code", 4);
            result.put("msg", "发送验证码出现异常");
            return result;
        }

    }


}

